package com.webtest.filter;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.FilterChain;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * @author lzy
 * @version v1.0
 * Create DateTime: 2018/8/15 19:27
 */
public class LoginFilter extends AbstractHttpFilter {
    private static final Logger LOGGER = LoggerFactory.getLogger(LoginFilter.class);

    // 从web.xml中获取sessionKey,redirectUrl,uncheckedUrls
    private String sessionKey;
    private String redirectUrl;
    private List<String> uncheckedUrls;

    @Override
    protected void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        //1.获取请求的servletPath
        //url:http://localhost:6086/webtest/login/list.jsp
        String requestUrl = request.getRequestURL().toString();
        //uri:/webtest/login/list.jsp
        String requestUri = request.getRequestURI();
        //path:/login/list.jsp
        String servletPath = request.getServletPath();

        LOGGER.info("url:" + requestUrl);
        LOGGER.info("uri:" + requestUri);
        LOGGER.info("path:" + servletPath);

        //2.检查1获取的servletPath是否为不需要检查的URL中的一个，若是，则直接放行，方法结束
        if (uncheckedUrls.contains(servletPath)) {
            chain.doFilter(request, response);
            return;
        }
        //3.从session获取sessionKey对应的值，若不存在，则重定向到redirectUrl
        String v = (String) request.getSession().getAttribute(sessionKey);
        if (StringUtils.isEmpty(v)) {
            response.sendRedirect(request.getContextPath() + redirectUrl);
            return;
        }
        //4.若存在，则放行，允许访问
        chain.doFilter(request, response);
    }

    @Override
    protected void init() {
        ServletContext context = getFilterConfig().getServletContext();
        this.sessionKey = context.getInitParameter("userSessionKey");
        this.redirectUrl = context.getInitParameter("redirectPage");
        String uncheckedUrlsStr = context.getInitParameter("uncheckedUrls");
        this.uncheckedUrls = Arrays.asList(uncheckedUrlsStr.trim().split(","));
    }
}
